<?php

namespace App\Http\Controllers\Backend;

use App\Http\Repositories\ArticlesRepository;
use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\ArticlesRequest;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
    protected $articlesRepository;

    public function __construct(ArticlesRepository $articlesRepository)
    {
        $this->articlesRepository = $articlesRepository;
    }

    /**
     * 文章列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        return responseResult($this->articlesRepository->getList($request->all()), self::SUCCESS_CODE);
    }

    /**
     * 创建文章
     * @param ArticlesRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(ArticlesRequest $request)
    {
        $result = $this->articlesRepository->edit($request->except("tag"), $request->get("tag"));
        return responseResult([], $result ? self::SUCCESS_CODE : self::ERROR_CODE);
    }

    /**
     * 更新文章
     * @param ArticlesRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(ArticlesRequest $request)
    {
        $result = $this->articlesRepository->edit($request->except("tag", "id"), $request->get("tag"), $request->get("id"));
        return responseResult([], $result ? self::SUCCESS_CODE : self::ERROR_CODE);
    }

    /**
     * 修改文章状态
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeEnable($id, Request $request)
    {
        $this->validate($request, ['status' => 'required']);
        $result = $this->articlesRepository->changeEnable($id, $request->get("status"));
        return responseResult([], $result ? self::SUCCESS_CODE : self::ERROR_CODE);
    }

    /**
     * 删除文章
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function del($id)
    {
        $result = $this->articlesRepository->del($id);
        return responseResult([], $result ? self::SUCCESS_CODE : self::ERROR_CODE);
    }

    /**
     * 归档
     * @return \Illuminate\Http\JsonResponse
     */
    public function getArchive()
    {
        return responseResult($this->articlesRepository->getArchive(), self::SUCCESS_CODE);
    }
}
